package per.poker.common;


import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
public class CommonService {

    private CommonService() {
    }

    /**
     * 只能用于按钮事件
     *
     * @param back
     * @param fxml
     */
    public static void jumpButtonEvent(Node back, String fxml) {
        Stage stage = (Stage) back.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader(CommonService.class.getResource(CharSequenceUtil.format("/scene/{}.fxml", fxml)));
        Scene scene;
        try {
            scene = new Scene(fxmlLoader.load());
        } catch (IOException e) {
            log.error("Failed to load fxml", e);
            return;
        }
        if (stage != null) {
            stage.setScene(scene);
        }
    }

    public static InputStream getPicUrl(String url) {
        if (ObjectUtil.isNull(CommonService.class.getResource(url))) {
            log.error("null:{}", url);
        }
        return Objects.requireNonNull(CommonService.class.getResourceAsStream(url));
    }

    public static void errorDialog(String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(null);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void runLater(Runnable runnable) throws InterruptedException {
        Object o = new Object();
        Platform.runLater(() -> {

            runnable.run();
            synchronized (o) {
                o.notifyAll();
            }
        });

        synchronized (o) {
            o.wait();
        }
    }
}
